#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
生成ABI语义分析的汇总报告
"""

import json
import sys
from pathlib import Path
from collections import Counter

try:
    import pandas as pd
    import openpyxl
    from openpyxl.styles import Font, PatternFill, Alignment
    HAS_EXCEL = True
except ImportError:
    HAS_EXCEL = False


def main():
    """生成汇总报告"""
    project_root = Path(__file__).parent.parent.parent
    analyzed_dir = project_root / 'output' / 'analyzed'
    
    # 获取所有分析结果JSON
    json_files = sorted(analyzed_dir.glob('*.analyzed.analyzed.json'))
    
    if not json_files:
        print("[ERROR] 没有找到分析结果文件")
        return 1
    
    print(f"[INFO] 找到 {len(json_files)} 个分析结果")
    
    # 收集所有库的统计数据
    library_stats = []
    all_functions = []
    
    for json_file in json_files:
        with open(json_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        lib_name = data['library']
        analyses = data['analyses']
        
        if not analyses:  # 跳过没有函数的库
            continue
        
        # 统计该库的数据
        total = len(analyses)
        stateful = len([a for a in analyses if a['statefulness'] == 'stateful'])
        stateless = len([a for a in analyses if a['statefulness'] in ['stateless', 'likely_stateless']])
        
        # 协议分类
        protocols = Counter(a['protocol_category'] for a in analyses)
        main_protocol = protocols.most_common(1)[0][0] if protocols else 'unknown'
        
        # 复杂度
        high_complexity = len([a for a in analyses if a['complexity'] == 'high'])
        
        # 风险
        high_risk = len([a for a in analyses if a['risk_level'] == 'high'])
        
        library_stats.append({
            '库名': lib_name,
            '总函数数': total,
            '有状态': stateful,
            '无状态': stateless,
            '有状态占比': f"{stateful/total*100:.1f}%",
            '主要协议': main_protocol,
            '高复杂度': high_complexity,
            '高风险': high_risk
        })
        
        # 收集所有函数（用于后续详细分析）
        for a in analyses:
            all_functions.append({
                '库名': lib_name,
                '函数名': a['function_name'],
                '类名': a['class_name'],
                '完整签名': a['demangled_name'][:100],  # 限制长度
                '命名空间': a['namespace'],
                '状态性': a['statefulness'],
                '状态评分': a['statefulness_score'],
                '协议': a['protocol_category'],
                '域': a['domain_category'],
                '调用模式': a['call_pattern'],
                '复杂度': a['complexity'],
                '风险': a['risk_level'],
                '线程安全': a['thread_safety']
            })
    
    # 生成Excel报告
    if HAS_EXCEL:
        output_file = project_root / 'output' / 'OPENBMC_ABI_ANALYSIS_SUMMARY.xlsx'
        
        # 重新组织数据：库 -> 命名空间 -> 类 -> 方法 + 属性
        hierarchical_data = []
        for func in all_functions:
            hierarchical_data.append({
                '库': func['库名'],
                '命名空间': func['命名空间'] or '(global)',
                '类': func.get('类名', '') or '(无类)',
                '方法': func['函数名'] or '(匿名)',
                '完整签名': func['完整签名'],
                # 属性列
                '有状态': '是' if func['状态性'] == 'stateful' else '否',
                '状态评分': func['状态评分'],
                '协议类型': func['协议'],
                '功能域': func['域'],
                '调用模式': func['调用模式'],
                '复杂度': func['复杂度'],
                '风险级别': func['风险'],
                '线程安全': func['线程安全']
            })
        
        df_hierarchical = pd.DataFrame(hierarchical_data)
        
        # 按库 -> 命名空间 -> 类 -> 方法排序
        df_hierarchical = df_hierarchical.sort_values(
            by=['库', '命名空间', '类', '方法'],
            key=lambda x: x.str.lower() if x.dtype == 'object' else x
        )
        
        with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
            # 主Sheet: 层次化的完整视图
            df_hierarchical.to_excel(writer, sheet_name='完整ABI清单', index=False)
            
            # 辅助Sheet 1: 按库统计
            df_libs = pd.DataFrame(library_stats)
            df_libs = df_libs.sort_values('总函数数', ascending=False)
            df_libs.to_excel(writer, sheet_name='按库统计', index=False)
            
            # 辅助Sheet 2: 整体统计
            df_all = pd.DataFrame(all_functions)
            summary_data = {
                '统计项': ['总函数数', '有状态函数', '无状态函数', '有状态占比',
                          '高复杂度', '高风险', 'DBus协议', 'IPMI协议', 'PLDM协议', 'MCTP协议'],
                '数值': [
                    len(df_all),
                    len(df_all[df_all['状态性'] == 'stateful']),
                    len(df_all[df_all['状态性'].isin(['stateless', 'likely_stateless'])]),
                    f"{len(df_all[df_all['状态性'] == 'stateful'])/len(df_all)*100:.1f}%",
                    len(df_all[df_all['复杂度'] == 'high']),
                    len(df_all[df_all['风险'] == 'high']),
                    len(df_all[df_all['协议'] == 'dbus']),
                    len(df_all[df_all['协议'] == 'ipmi']),
                    len(df_all[df_all['协议'] == 'pldm']),
                    len(df_all[df_all['协议'] == 'mctp'])
                ]
            }
            df_summary = pd.DataFrame(summary_data)
            df_summary.to_excel(writer, sheet_name='整体统计', index=False)
        
        # 美化Excel
        _format_excel(output_file)
        
        print(f"[SUCCESS] 汇总报告已生成: {output_file}")
        
        # 打印统计
        print("\n" + "=" * 80)
        print("OpenBMC ABI语义分析汇总")
        print("=" * 80)
        print(f"分析库数: {len(library_stats)}")
        print(f"总函数数: {len(df_hierarchical)}")
        
        stateful_count = len(df_hierarchical[df_hierarchical['有状态'] == '是'])
        stateless_count = len(df_hierarchical[df_hierarchical['有状态'] == '否'])
        print(f"有状态函数: {stateful_count} ({stateful_count/len(df_hierarchical)*100:.1f}%)")
        print(f"无状态函数: {stateless_count} ({stateless_count/len(df_hierarchical)*100:.1f}%)")
        
        print(f"\n按协议分类:")
        for protocol, count in Counter(df_hierarchical['协议类型']).most_common():
            print(f"  {protocol}: {count}")
        print("=" * 80)
    else:
        print("[ERROR] 需要安装pandas和openpyxl")
        return 1
    
    return 0


def _format_excel(excel_path: Path):
    """美化Excel表格"""
    wb = openpyxl.load_workbook(excel_path)
    
    header_fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
    header_font = Font(bold=True, color="FFFFFF")
    
    for sheet in wb.worksheets:
        # 设置表头样式
        if sheet.max_row > 0:
            for cell in sheet[1]:
                cell.fill = header_fill
                cell.font = header_font
                cell.alignment = Alignment(horizontal='center', vertical='center')
        
        # 自动调整列宽
        for column in sheet.columns:
            max_length = 0
            column_letter = column[0].column_letter
            for cell in column:
                try:
                    if cell.value:
                        max_length = max(max_length, len(str(cell.value)))
                except:
                    pass
            adjusted_width = min(max_length + 2, 80)
            sheet.column_dimensions[column_letter].width = adjusted_width
    
    wb.save(excel_path)


if __name__ == '__main__':
    sys.exit(main())

